package com.pd.backend.service.logistics.impl;

import com.pd.backend.common.R;
import com.pd.backend.domain.entity.PdAgency;
import com.pd.backend.domain.pojo.Agency;
import com.pd.backend.mapper.AgencyMapper;
import com.pd.backend.service.logistics.AgencyService;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.BEncoderStream;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 机构业务层实现类
 */
@Service
public class AgencyServiceImpl implements AgencyService {

    @Autowired
    private AgencyMapper agencyMapper;


    // TODO  只能查两层
    @Override
    public R<List<Agency>> getTree() {
        // 查询数据
        List<Agency> dbList = agencyMapper.getTree();
        // 将一级与机构放入集合中
        List<Agency> oneAgency = new ArrayList<>();
        for (Agency agency : dbList) {
            if ("0".equals(agency.getAgencyId())) {
                oneAgency.add(agency);
            }
        }

        // 递归查询机构树
        List<Agency> resultAgency = getAgencyChild(dbList, oneAgency);
        return R.success(resultAgency);
    }


    public List<Agency> getAgencyChild(List<Agency> dbAgencyList, List<Agency> parentList) {
        // 遍历最顶层
        for (int i = 0; i < parentList.size(); i++) {
            // 获取每个父机构
            Agency parentAgency = parentList.get(i);
            // 创建子集集合
            List<Agency> childList = new ArrayList<>();
            // 遍历全部机构
            for (int j = 0; j < dbAgencyList.size(); j++) {
                // 获取每个机构
                Agency childAgency = dbAgencyList.get(j);
                // 如果一次di是其他的父id  那么 这条数据就是一级的子集
                if (childAgency.getAgencyId().equals(parentAgency.getId())) {
                    childList.add(childAgency);
                }
            }
            if (childList != null && childList.size() > 0){
                parentList.get(i).setSubAgency(getAgencyChild(dbAgencyList,childList));
            }
            parentList.get(i).setSubAgency(childList);
        }
        return parentList;
    }
}
